# -*- coding:UTF-8 -*-
"""
Created on Thu Mar 14 21:25:45 2019

@author: DadaYu
"""
import requests
from bs4 import BeautifulSoup
import smtplib
from email.mime.text import MIMEText
import config

def resolveUrl(url):
    res = requests.get(url)
    res.encoding = 'utf-8'
    html = res.text
    bf = BeautifulSoup(html, "html5lib")
    a = bf.find('div', class_='content_list normal_list on').find('ul',class_='story_list').find_all('a')[0]
    print(url + a.get('href'))
    return url + a.get('href')

def getStory(url):
    # 这里用QQ举例需要其他请自行添加
    msg_from = 'wxvew3@126.com'  # 发送方邮箱
    passwd = 'TNCYLBSFJWNMPMJGA'  # 填入发送方邮箱的授权码
    receivers = config.EMAIL_LIST  # 收件人邮箱

    res = requests.get(resolveUrl(url))
    res.encoding = 'utf-8'
    html = res.text
    bf = BeautifulSoup(html, "html5lib")
    title = bf.find('div',class_= 'title').find('h1')
    subject = '今日份的睡前小故事--' + title.text
    story = bf.find('div',class_='article_content').find_all('p')
    content = ''

    for s in story:
        s = s.text.replace('\xa0' * 8, '\n\n')
        s = s.replace(u'\u3000', u' ')
        content = content + s

    msg = MIMEText(content)
    msg['Subject'] = subject
    msg['From'] = msg_from
    msg['To'] = ','.join(receivers)
    print(subject)
    print(content)
    try:
        s = smtplib.SMTP_SSL("smtp.126.com", 465)  # 邮件服务器及端口号
        s.login(msg_from, passwd)
        s.sendmail(msg_from, msg['To'].split(','), msg.as_string())
        print("发送成功")
    except:
        print("发送失败")
    finally:
        s.quit()

if __name__ == '__main__':
    getStory('https://www.qigushi.com')

